﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Management;
using System.Text;
using System.Windows.Forms;

namespace WMI_AdvancedQuery
{
    public partial class Form1 : Form
    {
        ConnectionOptions wmiconnection = new ConnectionOptions();
        List<string> listahost = new List<string>();
        string csvseparator;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetCredential_inwmiconnection();
            textBox_Host.Text = "localhost";


            #region Debug
            comboBox_Scope_Classes.Items.Add(@"\root\cimv2");
            #endregion
        }

        private void SetCredential_inwmiconnection()
        {
            if (checkBox_Account.CheckState == CheckState.Unchecked)
            {
                textBox_username.Enabled = true;
                textBox_password.Enabled = true;
                label_username.Enabled = true;
                label_password.Enabled = true;
                wmiconnection.Username = textBox_username.Text;
                wmiconnection.Password = textBox_password.Text;
            }
            else
            {
                textBox_username.Enabled = false;
                textBox_password.Enabled = false;
                label_username.Enabled = false;
                label_password.Enabled = false;
                wmiconnection.Username = null;
                wmiconnection.Password = null;
            }
                wmiconnection.EnablePrivileges = true;
                wmiconnection.Impersonation = ImpersonationLevel.Impersonate;
        }

        private void checkBox_Account_CheckedChanged(object sender, EventArgs e)
        {
            SetCredential_inwmiconnection();
        }
        
        private void button_Run_Click(object sender, EventArgs e)
        {
            listBox_output.Items.Clear();
            if (radioButton1.Checked == true)
            {
                Run_Wmi_Query(textBox_Host.Text);
            }
            else
            {
                foreach (string nomehost in listahost)
                {
                    Run_Wmi_Query(nomehost);
                }
            }
        }

        private void Run_Wmi_Query(string host)
        {
            bool stampaheader = false;
            if (radioButton3.Checked == true)
            {
                try
                {
                    listBox_output.Items.Add("########  " + host + "  ########");
                    ManagementScope wmiscope = new ManagementScope(@"\\" + host + comboBox_Scope_Classes.Text, wmiconnection);
                    ObjectQuery wmiquery = new ObjectQuery(QueryEditor.Text);
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiscope, wmiquery);
                    int counter = 1;
                    foreach (ManagementObject wmiobj in searcher.Get())
                    {
                        listBox_output.Items.Add(" ******  object:" + counter + "  ******");
                        PropertyDataCollection searcherproperties = wmiobj.Properties;
                        foreach (PropertyData pd in searcherproperties)
                        {
                            if (checkedListBox_Properties.CheckedItems.Contains(pd.Name))
                            {
                                listBox_output.Items.Add(pd.Name + " : " + pd.Value);
                            }
                        }
                        counter++;
                        listBox_output.SelectedIndex = listBox_output.Items.Count - 1;
                        Refresh();
                    }
                    searcher.Dispose();
                }
                catch (Exception e)
                {
                    listBox_output.Items.Add("########  " + host + "Error " + e.Message);
                }
            }
            else
            {
                try
                {
                    StringBuilder header = new StringBuilder();
                    StringBuilder linea = new StringBuilder();
                    if (listBox_output.Items.Count == 0)
                    {
                        stampaheader = true;
                        header.Append("HOST");
                        header.Append(csvseparator);
                        header.Append("Object n°");
                    }
                    ManagementScope wmiscope = new ManagementScope(@"\\" + host + comboBox_Scope_Classes.Text, wmiconnection);
                    ObjectQuery wmiquery = new ObjectQuery(QueryEditor.Text);
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiscope, wmiquery);
                    int counter = 1;
                    foreach (ManagementObject wmiobj in searcher.Get())
                    {
                        linea.Append(host);
                        linea.Append(csvseparator);
                        linea.Append(counter.ToString());
                        PropertyDataCollection searcherproperties = wmiobj.Properties;
                        foreach (PropertyData pd in searcherproperties)
                        {
                            if (checkedListBox_Properties.CheckedItems.Contains(pd.Name))
                            {
                                if (stampaheader == true)
                                {
                                    header.Append(csvseparator);
                                    header.Append(pd.Name);
                                }
                                linea.Append(csvseparator);
                                linea.Append(pd.Value);
                            }
                        }
                        if (stampaheader == true)
                        {
                            listBox_output.Items.Add(header.ToString());
                            stampaheader = false;
                        }
                        listBox_output.Items.Add(linea.ToString());
                        //linea.Clear();
                        linea.Remove(0, linea.Length);
                        counter++;
                        listBox_output.SelectedIndex = listBox_output.Items.Count - 1;
                        Refresh();
                    }
                    searcher.Dispose();
                }
                catch (Exception e)
                {
                    listBox_output.Items.Add(host + " ERROR " + e.Message);
                }
                
            }
        
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked == true)
            {
                textBox_Host.Enabled = true;
                CSV_Label.Visible = false;
            }
            else
            {
                textBox_Host.Enabled = false;
                CSV_Label.Visible = true;
            }
        }

        private void comboBox_Scope_Classes_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox_Wmi_Classes.Items.Clear();
            label_wmi.Text = "Wmi Classes - loading list...";
            Refresh();
            ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher(
                    new ManagementScope(comboBox_Scope_Classes.Text),
                    new WqlObjectQuery(
                    "select * from meta_class"),
                    null);
            foreach (ManagementClass wmiClass in
                searcher.Get())
            {
                comboBox_Wmi_Classes.Items.Add(
                    wmiClass["__CLASS"].ToString());
            }
            label_wmi.Text = "Wmi Classes";
            searcher.Dispose();
        }

        private void comboBox_Wmi_Classes_SelectedIndexChanged(object sender, EventArgs e)
        {
            checkedListBox_Properties.Items.Clear();
            label_properties.Text = "Properties - loading...";
            Refresh();
            ManagementClass Mclass = new ManagementClass(comboBox_Scope_Classes.Text, comboBox_Wmi_Classes.Text, null);
            Mclass.Options.UseAmendedQualifiers = true;
            foreach (PropertyData DataOption in Mclass.Properties)
            {
                checkedListBox_Properties.Items.Add(DataOption.Name);
            }
            QueryEditor.Text = "SELECT * FROM " + comboBox_Wmi_Classes.Text;
            label_properties.Text = "Properties";
            Mclass.Dispose();
        }

        private void CSV_Label_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog fileOpen = new OpenFileDialog();
            if (fileOpen.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            else
            {
                StreamReader reader = new StreamReader(fileOpen.OpenFile(), Encoding.Default);
                string linea;
                if (listahost != null && listahost.Count >= 1) { listahost.Clear(); }
                while ((linea = reader.ReadLine()) != null)
                {
                    listahost.Add(linea);
                }
                CSV_Label.Text = fileOpen.SafeFileName;
            }
            fileOpen.Dispose();
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton3.Checked == true)
            {
                label_separator.Visible = false;
                textBox_separator.Visible = false;
            }
            else
            {
                label_separator.Visible = true;
                textBox_separator.Visible = true;
            }
        }

        private void textBox_separator_TextChanged(object sender, EventArgs e)
        {
            if (textBox_separator.Text == @"\t")
            {
                csvseparator = "\t";
            }
            else
            {
                csvseparator = textBox_separator.Text;
            }            
        }

        private void Button_export_Click(object sender, EventArgs e)
        {
            SaveFileDialog DialogSave = new SaveFileDialog();
            DialogSave.Filter = "CSV file (*.csv)|*.csv|Text file (*.txt)|*.txt|All files (*.*)|*.*";
            DialogSave.DefaultExt = "csv";
            DialogSave.AddExtension = true;
            if (DialogSave.ShowDialog() == DialogResult.OK)
            {
                TextWriter tw = new StreamWriter(DialogSave.FileName);
                foreach (string linea in listBox_output.Items)
                {
                    tw.WriteLine(linea);
                }
                tw.Close();
            }
            DialogSave.Dispose();



        }

        private void contextMenuStrip_Properties_Opening(object sender, CancelEventArgs e)
        {
            if (checkedListBox_Properties.Items.Count >= 1)
            {
                if (checkedListBox_Properties.Items.Count == checkedListBox_Properties.CheckedItems.Count)
                {
                    unCheckAllToolStripMenuItem.Enabled = true;
                    checkAllToolStripMenuItem.Enabled = false;
                }
                else
                {
                    checkAllToolStripMenuItem.Enabled = true;
                    unCheckAllToolStripMenuItem.Enabled = false;
                }
            }
        }

        private void checkAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < checkedListBox_Properties.Items.Count; i++)
            { 
                checkedListBox_Properties.SetItemCheckState(i,CheckState.Checked);
            }
        }

        private void unCheckAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < checkedListBox_Properties.Items.Count; i++)
            {
                checkedListBox_Properties.SetItemCheckState(i, CheckState.Unchecked);
            }
        }

        private void textBox_username_TextChanged(object sender, EventArgs e)
        {
            wmiconnection.Username = textBox_username.Text;
        }

        private void textBox_password_TextChanged(object sender, EventArgs e)
        {
            wmiconnection.Password = textBox_password.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AboutBox1 about = new AboutBox1();
            about.ShowDialog();
        }

        



        
    }
}
